<template>
  <div v-loading="loading">
    <div class="text-right mb-3" v-if="viewMode">
      <el-button @click="handlePrint">
        <i class="fa fa-fw fa-print"></i>
        打印
      </el-button>
      <el-button @click="handleExport" :loading="downloadLoading">
        <i class="fa fa-fw fa-download"></i>
        导出
      </el-button>
    </div>
    <div :id="printId">
      <table class="w-100">
        <tbody>
          <tr>
            <td colspan="5">
              <h3 class="text-center">{{ tableTitle }}</h3>
            </td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">
              表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：G2表
            </td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">制表机关：中国银行保险监督管理委员会</td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">数据单位：家、人</td>
          </tr>
          <tr class="bd-0">
            <td colspan="3" width="50%" class="text-left">
              填报单位：{{ tableInfo.service_name || orgName }}
            </td>
            <td colspan="2" class="text-left">{{ dateLabel }}</td>
          </tr>
        </tbody>
      </table>

      <table class="table table-bordered text-center table-vertical-middle table-sm mb-0">
        <colgroup>
          <col width="47%" />
          <col width="5%" />
          <col width="16%" />
          <col width="16%" />
          <col width="16%" />
        </colgroup>
        <tbody>
          <tr class="bd-1">
            <td rowspan="3">项目</td>
            <td rowspan="3">代码</td>
            <td>A</td>
            <td>B</td>
            <td>C</td>
          </tr>
          <tr class="bd-1">
            <td colspan="3">期末数</td>
          </tr>
          <tr class="bd-1">
            <td>
              国有控股
              <div>融资担保机构</div>
            </td>
            <td>
              民营及外资
              <div>融资担保机构</div>
            </td>
            <td>合计</td>
          </tr>
          <tr v-for="item in editData" class="bd-1" :key="item.b">
            <td class="text-left" :class="item.style">{{ item.a }}</td>
            <td>{{ item.b }}</td>
            <td :class="item.notedit ? '' : tdClass">
              <span v-if="viewMode || item.notedit">{{ item.c }}</span>
              <el-input
                v-else
                class="text-center"
                v-input-number="{ min: 0, fixed: item.fixed }"
                @input="setNotEditNumber"
                v-model="item.c"
              ></el-input>
            </td>
            <td :class="item.notedit ? '' : tdClass">
              <span v-if="viewMode || item.notedit">{{ item.d }}</span>
              <el-input
                v-else
                class="text-center"
                v-input-number="{ min: 0, fixed: item.fixed }"
                @input="setNotEditNumber"
                v-model="item.d"
              ></el-input>
            </td>
            <td>{{ add(item.c, item.d) || '' }}</td>
          </tr>
        </tbody>
      </table>

      <table class="w-100">
        <tbody>
          <tr>
            <td class="text-left" width="30%">统计负责人：</td>
            <td colspan="2" width="40%">
              填表人及联系方式：{{ tableInfo.submit_person_name || user.realName }}
              {{ tableInfo.phone_number || user.phoneNumber }}
            </td>
            <td colspan="2" width="30%">报出日期：{{ createDate }}</td>
          </tr>
          <tr>
            <td colspan="5" class="text-left" rowspan="7">
              <div class="mt-3">
                <pre class="report-desc">{{ reportDesc }}</pre>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="mb-5 text-center" v-if="!viewMode">
      <el-button :loading="saveLoading" class="btn-long" type="primary" @click="save">
        保存
      </el-button>

      <el-button class="mr-2 btn-long" :loading="saveLoading" @click="beforeClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { add, excelTableExport, domHasClass, printWithIframe } from '@vimi/utils-tool'
export default {
  components: {},
  props: {
    queryYear: {
      type: Number,
      required: true,
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      tableData: [
        {
          a: '本省（区、市）融资担保机构数量',
          b: '201',
          c: '',
          d: '',
          e: '',
          fixed: 0,
          notedit: true,
        },
        {
          a: '其中：法人机构数量',
          b: '202',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-1',
          fixed: 0,
          notedit: true,
        },
        {
          a: '其中：实收资本50亿元(含)以上',
          b: '203',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-3',
          fixed: 2,
        },
        {
          a: '实收资本10亿元(含)-50亿元',
          b: '204',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-4',
          fixed: 2,
        },
        {
          a: '实收资本1亿元(含)-10亿元',
          b: '205',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-4',
          fixed: 2,
        },
        {
          a: '实收资本 2000万元(含)-1亿元',
          b: '206',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-4',
          fixed: 2,
        },
        {
          a: '其中：融资再担保机构',
          b: '207',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-3',
          fixed: 0,
        },
        { a: '分支机构数量', b: '208', c: '', d: '', e: '', style: 'text-indent-2', fixed: 0 },
        {
          a: '其中：外省（区、市）在本省（区、市）设立的',
          b: '209',
          c: '',
          d: '',
          e: '',
          style: 'text-indent-3',
          fixed: 0,
        },
        { a: '从业人数', b: '210', c: '', d: '', e: '', fixed: 0 },
      ],
      reportDesc: `填报说明：
1.本表由各省、自治区、直辖市融资担保公司监督管理部门填报。
2.本表统计范围为在本省（区、市）持有融资担保业务经营许可证的融资担保机构和外省（区、市）融资担保法人机构在本省（区、市）设立的分支机构，但不含本省（区、市）融资担保法人机构在省（区、市）外设立的分支机构。
3.填列的金额按四舍五入保留整数。
4.本报表为年报，报送时间为年后1月底前。
5.校验关系：[A]+[B]=[C]，[202]+[208]=[201]，[203]+[204]+[205]+[206]=[202]。
`,
      downloadLoading: false,
      loading: false,
      tableName: 'report_year',
      tableTitle: 'XX省（区、市）融资担保公司及人员情况',
      params: {
        'year_type.eq': 5,
        subKey: 'report_year_person_detail.report_year_id',
      },
      tableInfo: {},
      order: {},
      saveLoading: false,
      editData: [],
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'clientId']),
    orgName() {
      return this.org.orgName
    },
    dateLabel() {
      return `${this.queryYear}年`
    },
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    createDate() {
      return this.$utils.dateFormat(this.tableInfo.update_time, 'yyyy年MM月dd日')
    },
    printId() {
      return `${this.queryYear}-g2`
    },
  },
  watch: {
    queryYear: {
      handler: function () {
        this.params['service_id.eq'] = this.clientId
        this.params['year_number.eq'] = this.queryYear
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    add,
    setNotEditNumber() {
      this.$set(this.editData[1], 'c', this.sumKey('c', [203, 204, 205, 206]))
      this.$set(this.editData[1], 'd', this.sumKey('d', [203, 204, 205, 206]))
      this.$set(this.editData[0], 'c', this.sumKey('c', [202, 208]))
      this.$set(this.editData[0], 'd', this.sumKey('d', [202, 208]))
    },
    sumKey(key, arr) {
      let sum = 0
      arr.forEach(order => {
        const addItem = this.editData.find(item => +item.b === order) || {}
        sum += +addItem[key] || 0
      })
      return sum || ''
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          this.tableInfo = res?.data?.[0] ?? {}
          const data = this.tableInfo.report_year_person_detail || []
          this.tableData = this.tableData.map(item => {
            const row = data.find(d => d.dimension_key === item.b) || {}
            item.c = row.com_person_total || ''
            item.d = row.un_person_total || ''
            item.id = row.id
            return item
          })
          this.editData = this.tableData.map(item => {
            return { ...item }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    save() {
      const masterData = {
        year_type: 5,
        report_no: 'G2表',
        report_name: this.tableTitle,
        res_person: this.user.realName,
        phone_number: this.user.phoneNumber,
        year_number: this.queryYear,
        service_id: this.clientId,
        submit_person_name: this.user.realName,
        service_name: this.orgName,
      }
      if (this.tableInfo.report_year_id) {
        masterData.report_year_id = this.tableInfo.report_year_id
      }
      const slaveData = this.editData.map(item => {
        const data = {
          com_person_total: item.c || 0,
          un_person_total: item.d || 0,
          total_funds: add(item.c, item.d),
          order_num: item.b,
          dimension_key: item.b,
          dimension_key_name: item.a,
        }
        if (this.tableInfo.report_year_id) {
          data.report_year_id = this.tableInfo.report_year_id
          data.id = item.id
        }
        return data
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'report_year_person_detail',
      }
      this.saveLoading = true
      if (this.tableInfo.report_year_id) {
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    beforeClose() {
      this.editData = this.tableData.map(item => {
        return { ...item }
      })
      this.$emit('close', false)
    },
    handlePrint() {
      printWithIframe(document.getElementById(this.printId))
    },
    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const borderAllNone = {
        left: { style: 'none' },
        top: { style: 'none' },
        right: { style: 'none' },
        bottom: { style: 'none' },
      }

      this.downloadLoading = true
      excelTableExport(this.printId, this.tableTitle, {
        styles: {
          border: borderAllNone,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 24,
              name: '方正小标宋简体',
            },
          },
          A34: {
            alignment: {
              vertical: 'top',
              wrapText: true,
            },
          },
          A7: {
            border: borderAllThin,
          },
        },
        cols: [{ wch: 40.63 }, { wch: 10.0 }, { wch: 28.0 }, { wch: 24.0 }, { wch: 24.0 }],
        rows: {
          0: { hpx: 48 },
          33: { hpx: 180 },
        },
        cellHandler({ value, tr, td }) {
          const style = {}

          if (domHasClass(tr, 'bd-1')) {
            style.border = borderAllThin
          } else if (domHasClass(tr, 'bd-0')) {
            style.border = borderAllNone
          }

          if (domHasClass(td, 'text-right')) {
            style.alignment = { horizontal: 'bottom' }
          } else if (domHasClass(td, 'text-left')) {
            style.alignment = { horizontal: 'top' }
          }

          const { className = '' } = td
          const indent = /text-indent-(\d+)/.exec(className)
          if (indent) {
            value = `${' '.repeat(+(indent[1] || 0) * 8)}${value}`
          }

          return { value, style }
        },
      }).finally(() => {
        this.downloadLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
$indents: 1, 2, 3, 4;
@each $i in $indents {
  .text-indent-#{$i} {
    text-indent: $i * 2rem;
  }
}

.report-desc {
  font-size: 1rem;
  white-space: pre-wrap;
  font-family: 'Microsoft Yahei', '\5FAE\8F6F\96C5\9ED1', Helvetica, Arial, sans-serif;
}
.input-td {
  background-color: #ffffee;
}
.bd-0 > td {
  border: none;
}

.bd-1 > td {
  border: 1px solid $border-color;
}
</style>
